package com.bingo.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bingo.demo.pojo.Album;
import com.bingo.demo.pojo.Essay;
import com.bingo.demo.pojo.User;
import com.bingo.demo.service.AlbumService;
import com.bingo.demo.service.EssayService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ViewController {

    @Autowired
    private EssayService essayService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping({"/","/index","toIndex.action","index.html"})
    public String toIndex(HttpSession session){
        List<Essay> essayList = new ArrayList<>();
        //将第一页数据缓存到redis中,如果不存在则缓存,若存在则直接取用,不再访问数据库
        try {
            ValueOperations opsForValue = redisTemplate.opsForValue();
            String page = (String)opsForValue.get("page");
            if(page != null){
                //redis中存在第一页数据
                JSONArray jsonArray = JSONArray.parseArray(page);
                essayList = jsonArray.toJavaList(Essay.class);
                System.out.println("redis中存在第一页数据");
            }else {
                //redis中不存在第一页数据
                //参数为1,表示权限为公开的文章
                essayList = essayService.findByAuthoruty(1);
                //存入redis
                String json = JSON.toJSONString(essayList);
                opsForValue.set("page",json);
                System.out.println("redis中不存在第一页数据");
            }
        }catch (Exception e){
            essayList = essayService.findByAuthoruty(1);
        }finally {
            //只返回5条数据
            if(essayList.size() > 5){
                List<Essay> list = essayList.subList(0, 5);
                session.setAttribute("essayList",list);
                session.setAttribute("hasNext",1);
            }else {
                session.setAttribute("essayList",essayList);
                session.setAttribute("hasNext",0);
            }
            session.setAttribute("hasLast",0);
            session.setAttribute("pageNum",1);
            session.setAttribute("oldPageNum",0);
            return "index";
        }


    }

    @RequestMapping("toNextPage.action")
    public String toNextPage(HttpSession session){
        if(session.getAttribute("hasNext").equals(0))return "index";
        Integer page=1;
        Object pageNum = session.getAttribute("pageNum");
        if(pageNum!=null){
            page = (Integer)pageNum+1;
        }
        List<Essay>essayList;
        try {
            //参数为1,表示权限为公开的文章
            //List<Essay> essayList = essayService.findByAuthoruty(1);
            //从redis中取出数据列表
            try {
                ValueOperations opsForValue = redisTemplate.opsForValue();
                String page1 = (String)opsForValue.get("page");
                JSONArray jsonArray = JSONArray.parseArray(page1);
                essayList = jsonArray.toJavaList(Essay.class);
            }catch (Exception e1){
                //1代表权限为公开的文章
                essayList = essayService.findByAuthoruty(1);
            }
            //选择页数
            if(essayList.size() > page*5){
                List<Essay> list = essayList.subList((page-1)*5, page*5-1);
                session.setAttribute("essayList",list);
            }else{
                List<Essay> list = essayList.subList((page-1)*5,essayList.size());
                session.setAttribute("essayList",list);
                session.setAttribute("hasNext",0);
            }
            session.setAttribute("pageNum",page);
            //如果这个跳转下一页的方法被调用,则说明必有上一页
            session.setAttribute("hasLast",1);
        } catch (IllegalArgumentException e) {
            page = page-1;
            session.setAttribute("hasNext",0);
            session.setAttribute("pageNum",page);
            return "index";
        }
        return "index";
    }

    @RequestMapping("toLastPage.action")
    public String toLastPage(HttpSession session){
        Integer page=1;
        Object n = session.getAttribute("pageNum");
        if(n != null){
            page = (Integer)n-1;
        }
        List<Essay> essayList;
        try {
            //此方法被调用,则必有下一页
            session.setAttribute("hasNext",1);
            //参数为1,表示权限为公开的文章
            //List<Essay> essayList= essayService.findByAuthoruty(1);
            try {
                ValueOperations opsForValue = redisTemplate.opsForValue();
                String page1 = (String)opsForValue.get("page");
                JSONArray jsonArray = JSONArray.parseArray(page1);
                essayList = jsonArray.toJavaList(Essay.class);
            }catch (Exception e1){
                //1代表为权限为公开的文章
                essayList = essayService.findByAuthoruty(1);
            }
            //选择页数
            List<Essay> list = essayList.subList((page - 1) * 5, page * 5 - 1);
            session.setAttribute("essayList",list);
            //如果当前页为首页,则无上一页
            if(page == 1)session.setAttribute("hasLast",0);
            //返回之前设置新的页码
            session.setAttribute("pageNum",page);
        } catch (Exception e) {
            page = page+1;
            session.setAttribute("pageNum",page);
            return "index";
        }
        return "index";
    }

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("toWrite.action")
    public String toWrite(HttpSession session, Model model){
        if(session.getAttribute("loginUser") == null){
            model.addAttribute("msg","您还没有登录,请先登录");
            return "login";
        }
        User user = (User) session.getAttribute("loginUser");
        List<Album> albumList = albumService.findByUserId(user.getId());
        session.setAttribute("albumList",albumList);
        return "writeBlog";
    }

    @RequestMapping("toAbout.action")
    public String toAbout(HttpSession session, Model model){
        if(session.getAttribute("loginUser") == null){
            model.addAttribute("msg","您还没有登录,请先登录");
            return "login";
        }
        User user = (User) session.getAttribute("loginUser");
        List<Album> list = albumService.findByUserId(user.getId());
        if(!list.isEmpty()){
            session.setAttribute("mainAlbumUrl",list.get(list.size()-1).getImgUrl());
        }else {
            session.setAttribute("mainAlbumUrl","img/empty.jpg");
        }
        return "about";
    }

    @RequestMapping("toLogout")
    public String toLogout(HttpServletResponse response) throws IOException {
        Subject subject= SecurityUtils.getSubject();
        subject.logout();
        response.sendRedirect("/");
        return "index";
    }

    @RequestMapping("toRegister.action")
    public String toRegister(HttpSession session, Model model){
        return "register";
    }


}
